﻿/// <reference path="typings/jquery/jquery.d.ts" />
/// <reference path="typings/jquery/jqueryui.d.ts" />
/// <reference path="typings/jquery/jquery.tmpl.d.ts" />
/// <reference path="typings/linq.d.ts" />
/// <reference path="typings/linq.jquery.d.ts" />

interface JQuery {
    fileupload: any;
    sort: any;
    highlight: any;
}

interface JQueryStatic {
    fileDownload: any;
    Dialog: any;
}

declare var OData: any;

declare var moment: any;

module CloudStorageLight {

    export class FileItem {
        public Id: string;
        public Type: string;
        public Directory: string;
        public Title: string;
        public SearchContent: string;
        public Owner: string;
        public CheckoutUser: string;
        public LastModified: Date;
        public Remark: string;
        public Path: string;
        public Length: string;
        public FileProtectedMode: string;
        public AttachmentFileName: string;
        public OriginalUrl: string;

        public Url(): string {
            return StorageController.filesRootUrl + this.Path + window.location.search;
        }
        public WebPartUrl(): string {            
            return StorageController.webPartsRootUrl + this.Path + window.location.search;
        }
        public AttachmentUrl(): string {
            if (window.location.search) {
                return StorageController.filesRootUrl + this.Path + window.location.search + "&mode=attachment";
            } else {
                return StorageController.filesRootUrl + this.Path + "?mode=attachment";
            }
        }
        public ZipUrl(): string {
            if (window.location.search) {
                return StorageController.filesRootUrl + this.Path + window.location.search + "&mode=zip";
            } else {
                return StorageController.filesRootUrl + this.Path + "?mode=zip";
            }
        }
        public SizeString(): string {
            return this.formatFileSize(this.Length);
        }
        public CanDirectDownload(): boolean {
            if (this.pathEndsWith(this.AttachmentFileName)) return true;
            return false;
        }

        public LastModifiedString(): string {
            if (this.LastModified) {
                return new Date(this.LastModified.toString()).toLocaleString();
            } else {
                return "";
            }
        }
        public Icon(): string {
            if (this.Type == "Directory") return "icon-folder-2";
            if (this.pathEndsWith(".doc") || this.pathEndsWith(".docx")) {
                return "icon-file-word";
            }
            if (this.pathEndsWith(".ppt") || this.pathEndsWith(".pptx")) {
                return "icon-file-powerpoint";
            }
            if (this.pathEndsWith(".xls") || this.pathEndsWith(".xlsx")) {
                return "icon-file-excel";
            }
            if (this.pathEndsWith(".pdf")) {
                return "icon-file-pdf";
            }
            if (this.pathEndsWith(".zip")) {
                return "icon-file-zip";
            }
            return "icon-file";
        }

        private IsImage(): boolean {
            if (this.pathEndsWith(".jpg") || this.pathEndsWith(".jpeg")) {
                return true;
            }
            if (this.pathEndsWith(".png") || this.pathEndsWith(".gif")) {
                return true;
            }
            if (this.pathEndsWith(".bmp")) {
                return true;
            }
            return false;
        }

        private pathEndsWith(suffix: string) : boolean {
            return this.Path.indexOf(suffix, this.Path.length - suffix.length) !== -1;
        }

        private formatFileSize(bytes: any) {
            if (typeof bytes !== 'number') {
                return '';
            }

            if (bytes >= 1000000000) {
                return (bytes / 1000000000).toFixed(2) + ' GB';
            }

            if (bytes >= 1000000) {
                return (bytes / 1000000).toFixed(2) + ' MB';
            }

            return (bytes / 1000).toFixed(2) + ' KB';
        }

    }

    export class FileAccessToken {

        public role: string;
        public inUse: boolean;
        public canRead: boolean;
        public canWrite: boolean
        public canModify: boolean;
        public canControl: boolean;

        constructor(tokensString: string = null) {
            if (tokensString) {
                var items = tokensString.split(":");
                if (items.length != 2) throw new Error("invalid token string");
                this.role = items[0];
                var access: string = items[1];
                if (access.indexOf("r") >= 0) this.canRead = true;
                if (access.indexOf("w") >= 0) this.canWrite = true;
                if (access.indexOf("m") >= 0) this.canModify = true;
                if (access.indexOf("c") >= 0) this.canControl = true;
                this.inUse = true;
            }
        }

        public toString(): string {
            return this.role + ":" + (this.canRead ? "r" : "") + (this.canWrite ? "w" : "") + (this.canModify ? "m" : "") + (this.canControl ? "c" : "");
        }
    }

    export class SnapshotItem {
        public path: string;
        public downloadUrl: string;
        public snapshot: string;

        public Url(): string {
            if (this.downloadUrl.indexOf("?") >= 0) {
                return this.downloadUrl + "&snapshot=" + this.snapshot.split('|')[0];
            } else {
                return this.downloadUrl + "?snapshot=" + this.snapshot.split('|')[0];
            }
        }

        public Name(): string {
            return Enumerable.from(decodeURIComponent(this.path).split("/")).last();
        }

        public snapshotString(): string {
            return this.snapshot.split('|')[1];
        }
    }

    export class DeletedItem {
        public path: string;

        public Url(): string {
            return StorageController.filesRootUrl + this.path + "?deleted=true";
        }

        public Name(): string {
            return Enumerable.from(decodeURIComponent(this.path).split("/")).last();
        }

        public Icon(): string {
            if (this.pathEndsWith(".doc") || this.pathEndsWith(".docx")) {
                return "icon-file-word";
            }
            if (this.pathEndsWith(".ppt") || this.pathEndsWith(".pptx")) {
                return "icon-file-powerpoint";
            }
            if (this.pathEndsWith(".xls") || this.pathEndsWith(".xlsx")) {
                return "icon-file-excel";
            }
            if (this.pathEndsWith(".pdf")) {
                return "icon-file-pdf";
            }
            if (this.pathEndsWith(".zip")) {
                return "icon-file-zip";
            }
            return "icon-file";
        }

        private pathEndsWith(suffix: string): boolean {
            return this.path.indexOf(suffix, this.path.length - suffix.length) !== -1;
        }
    }

        export class AccessLogItem {
        public AccessDate: Date;
        public Path: string;
        public UserName: string;
        public Action: string;

        public Url(): string {
            return StorageController.filesRootUrl + this.Path;
        }

        public Name(): string {
            return Enumerable.from(decodeURIComponent(this.Path).split("/")).last();
        }

        public Icon(): string {
            if (this.pathEndsWith(".doc") || this.pathEndsWith(".docx")) {
                return "icon-file-word";
            }
            if (this.pathEndsWith(".ppt") || this.pathEndsWith(".pptx")) {
                return "icon-file-powerpoint";
            }
            if (this.pathEndsWith(".xls") || this.pathEndsWith(".xlsx")) {
                return "icon-file-excel";
            }
            if (this.pathEndsWith(".pdf")) {
                return "icon-file-pdf";
            }
            if (this.pathEndsWith(".zip")) {
                return "icon-file-zip";
            }
            return "icon-file";
        }
            private pathEndsWith(suffix: string): boolean {
                return this.Path.indexOf(suffix, this.Path.length - suffix.length) !== -1;
            }

            public AccessDateString(): string {
                if (this.AccessDate) {
                    return new Date(this.AccessDate.toString()).toLocaleString();
                } else {
                    return "";
                }
            }
    }

    export class StorageController {

        ///
        /// メッセージ定義
        ///
        public static msgRoleSelectorTitle: string;
        public static msgDownloadComplete: string;
        public static msgDownloadError: string;
        public static msgErrGeneral: string;
        public static msgPleaseChecked: string;
        public static msgConfirmDelete: string;
        public static msgCmdNewFolder: string;
        public static msgCmdFolderSetup: string;
        public static msgCmdUserList: string;
        public static msgConfirmDeleteFolder: string;
        public static msgChangePassword: string;
        public static msgUploading: string;
        public static msgDownloading: string;
        public static msgProcessing: string;
        public static msgCancel: string;
        public static msgPleaseReadMail: string;
        public static msgDuplicateRole: string;

        public static msgEditingOtherUser: string;
        public static msgUploadedCheckin: string;
        public static msgCheckoutAndDownload: string;
        public static msgUserInfoSettings: string;
        public static msgConfirmDeleteUser: string;
        public static msgConfirmDownloadZip: string;
        public static msgItemUrl: string;
        public static msgCmdRename: string;
        public static msgCmdMove: string;
        public static msgConfirmDeleteFile: string;
        public static msgConfirmDeleteCompletelyFile: string;
        public static msgConfirmCompetelyDelete: string;
        public static msgConfirmOverwriteUpload: string;
        public static msgHistoryNotFound: string;
        public static msgRecoverableFilesNotFound: string;
        public static msgSuccess: string;

        public static msgFoundItems: string;
        public static msgFoundOver: string;
        public static msgNotFound: string;
        public static msgUpdateUserData: string;
        public static msgNoAccessLog: string;
        public static msgFileTransfer: string;
        public static msgConfirmForceCheckin: string;
        public static msgCanceled: string;
        public static msg404Error: string;

        ///
        /// 共通変数
        ///
        public static contentMenuTarget: JQuery;
        private static uploadQue: any[] = [];
        private static currentUpload: any;
        private static allSuccess: boolean;
        public static xhrPool: any[] = [];

        public static rootUrl: string;
        public static filesRootUrl: string;
        public static webPartsRootUrl: string;
        public static helperRootUrl: string;
        public static oDataRootUrl: string;
        public static accountRootUrl: string;
        public static workTaskRootUrl: string;

        private static getEscapedPath(url: string): string {
            return encodeURIComponent(url.replace("'", "''"));
        }

        public static getFiles(target: JQuery, path: string, start:number=0, size:number=200, callback=null): void {
            StorageController.blockUI(null, false);
            $("#recover-command").hide();
            $("#move-command").show();
            $("#remove-command").show();
            $("#file-items tr.list").remove();
            $(".search-result-message").empty();
            $.ajax(StorageController.getODataUrl(null, null) + "?$filter=Directory eq '" + StorageController.getEscapedPath(path) + "'&$skip=" + start.toString() + "&$top=" + (size + 1).toString(), {
                type: "GET",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    var cont = $("#file-items");
                    if (data.value) {
                        Enumerable.from(data.value)
                            .orderBy(function (x: any) { return x.Type; })
                            .thenBy(function (x: any) { return x.Title; })
                            .take(size)
                            .doAction(function (x) {
                                var obj = <FileItem>$.extend(new FileItem(), x);
                                var ele = $("#fileitem-template").tmpl(obj);
                                cont.append(ele);
                                LyncUtil.addUserPanel(obj.Owner, obj.Owner, ele.find(".owner-userid"));
                            }).toArray();
                        if (data.value.length > size) {
                            var more = $("#fileitem-more-template").tmpl();
                            cont.append(more);
                        }
                    } else if (data.error && data.error.message) {
                        var cont = $("#info-message");
                        cont.append(StorageController.createErrorMessageElement(data.error.message));
                    }

                    StorageController.bindItemEvent();
                    StorageController.unblockUI();
                    if (callback) callback();
                },
                error: function (xhr, textStatus, errorThrown) {
                    var cont = $("#info-message");
                    cont.append(StorageController.createErrorMessageElement(StorageController.getErrorMessage(xhr)));
                    StorageController.unblockUI();
                },
                dataType: "json"
            });
        }

        public static listDeletedFiles(target: JQuery, path: string): void {
            StorageController.blockUI(null);
            StorageController.hideContextMenu(StorageController.contentMenuTarget);
            $("#recover-command").show();
            $("#move-command").hide();
            $("#remove-command").hide();
            $("#file-items tr.list").remove();
            $(".search-result-message").empty();
            $("#info-message").empty();
            $.ajax(StorageController.getODataUrl(path, "ListDeletedFiles"), {
                type: "GET",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    var cont = $("#file-items");
                    if (data.value) {
                        if (data.value.length > 0) {
                            Enumerable.from(data.value)
                                .doAction(function (x: any) {
                                    var obj = new DeletedItem();
                                    obj.path = x;
                                    var ele = $("#deleted-template").tmpl(obj);
                                    cont.append(ele);
                                }).toArray();
                        } else {
                            var cont = $("#info-message");
                            cont.append(StorageController.createErrorMessageElement(CloudStorageLight.StorageController.msgRecoverableFilesNotFound));
                        }
                    } else if (data.error && data.error.message) {
                        var cont = $("#info-message");
                        cont.append(StorageController.createErrorMessageElement(data.error.message));
                    }

                    StorageController.bindItemEvent();
                    StorageController.unblockUI();
                },
                error: function (xhr, textStatus, errorThrown) {
                    var cont = $("#info-message");
                    cont.append(StorageController.createErrorMessageElement(StorageController.getErrorMessage(xhr)));
                    StorageController.unblockUI();
                },
                dataType: "json"
            });
        }


        public static getVersions(target: JQuery, path: string, downloadUrl: string): void {
            StorageController.blockUI(null);
            $("#file-items tr.list").remove();
            $(".search-result-message").empty();
            $.ajax(StorageController.getODataUrl(path, "GetVersions"),{
                type: "GET",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    var cont = $("#file-items");
                    if (data.value) {
                        if (data.value.length > 0) {
                            Enumerable.from(data.value)
                                .doAction(function (x: any) {
                                    var obj = new SnapshotItem();
                                    obj.path = path;
                                    obj.downloadUrl = downloadUrl;
                                    obj.snapshot = x;
                                    var ele = $("#snapshot-template").tmpl(obj);
                                    cont.append(ele);
                                }).toArray();
                        } else {
                            var cont = $("#info-message");
                            cont.append(StorageController.createErrorMessageElement(CloudStorageLight.StorageController.msgHistoryNotFound));
                        }
                    } else if (data.error && data.error.message) {
                       var cont = $("#info-message");
                        cont.append(StorageController.createErrorMessageElement(data.error.message));
                    }

                    StorageController.bindItemEvent();
                    StorageController.unblockUI();
                },
                error: function (xhr, textStatus, errorThrown) {
                    var cont = $("#info-message");
                    cont.append(StorageController.createErrorMessageElement(StorageController.getErrorMessage(xhr)));
                    StorageController.unblockUI();
                },
                dataType: "json"
            });
        }

        public static getAccessLog(target: JQuery, path: string): void {
            StorageController.blockUI(null);
            StorageController.hideContextMenu(StorageController.contentMenuTarget);
            $("#file-items").empty();
            $(".search-result-message").empty();
            $.ajax(StorageController.getODataUrl(path, "GetAccessLog"), {
                type: "GET",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    var cont = $("#file-items");
                    if (data.value) {
                        if (data.value.length > 0) {
                            Enumerable.from(data.value)
                                .doAction(function (x: any) {
                                    var obj = <AccessLogItem>$.extend(new AccessLogItem(), x);
                                    var ele = $("#accesslog-template").tmpl(obj);
                                    cont.append(ele);
                                }).toArray();
                        } else {
                            cont.append(StorageController.createErrorMessageElement(StorageController.msgNoAccessLog));
                        }
                    } else if (data.error && data.error.message) {
                        cont.append(StorageController.createErrorMessageElement(data.error.message));
                    }

                    StorageController.bindItemEvent();
                    StorageController.unblockUI();
                },
                error: function (xhr, textStatus, errorThrown) {
                    var cont = $("#file-items");
                    cont.append(StorageController.createErrorMessageElement(StorageController.getErrorMessage(xhr)));
                    StorageController.unblockUI();
                },
                dataType: "json"
            });
        }

        public static searchFiles(target: JQuery, path: string, query : string, size: number= 2000): void {
            StorageController.blockUI(null);
            $("#file-items tr.list").remove();
            $(".search-result-message").empty();
            $.ajax(StorageController.getODataUrl(null, null) + "?$filter=startswith(Directory,'" + StorageController.getEscapedPath(path) + "')&$search='" + encodeURIComponent(query)  + "'&$top=" + (size + 1).toString(), {
                type: "GET",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    var cont = $("#file-items");
                    if (data.value) {
                        if (data.value.length == 0) {
                            var message = $(".search-result-message");
                            message.append(StorageController.createErrorMessageElement(StorageController.formatString(StorageController.msgNotFound,query)));
                        } else {
                            var message = $(".search-result-message");
                            if (data.value.length > size) {
                                message.append(StorageController.createErrorMessageElement(StorageController.formatString(StorageController.msgFoundOver, size)));
                            } else {
                                message.append(StorageController.createInfoMessageElement(StorageController.formatString(StorageController.msgFoundItems, data.value.length)));
                            }
                            Enumerable.from(data.value)
                                .take(size)
                                .doAction(function (x) {
                                    var obj = <FileItem>$.extend(new FileItem(), x);
                                    var ele = $("#fileitem-template").tmpl(obj);
                                    cont.append(ele);
                                }).toArray();
                            Enumerable.from(query.split(" "))
                                .doAction(function (x) {
                                    $(".item-description").highlight(x);
                                }).toArray();
                        }
                    } else if (data.error && data.error.message) {
                        cont.append(StorageController.createErrorMessageElement(data.error.message));
                    }
                    StorageController.bindItemEvent();
                    StorageController.unblockUI();
                },
                error: function (xhr, textStatus, errorThrown) {
                    var message = $(".search-result-message");
                    message.append(StorageController.createErrorMessageElement(StorageController.getErrorMessage(xhr)));
                    StorageController.unblockUI();
                },
                dataType: "json"
            });
        }

        ///
        /// 表示後のイベント割り当て
        ///
        public static bindItemEvent(cont:JQuery= null): void {

            var tapTimeoutId = 0;

            if (!cont) cont = $("#folder-cont");

            cont.find('.item-name').unbind().click(function (event) {
                var target = $(this).closest(".list-content").find(".item-checkbox");
                if (target.is(":visible")) target.prop("checked", !target.prop("checked"));
            });


            cont.find('.conetextMenuBtn').unbind().click(function (e) {
                StorageController.contentMenuTarget = $(this).closest(".list");
                StorageController.showContextMenu(StorageController.contentMenuTarget);
                e.stopPropagation();
            });



            $(".morePage").unbind().click(function () {
                CloudStorageLight.StorageController.morePage();
            });

            //$(window).unbind("bottom",true).one('bottom', function () {
            //    if ($(".morePage").length > 0) {
            //        CloudStorageLight.StorageController.morePage();
            //    }
            //});

            //cont.find('.blobfolder').click(function () {
            //    CloudStorageLight.StorageController.getFiles($("#file-items"), $(this).attr("data-path"));
            //});
        }

        ///
        /// コンテキストメニューの表示
        ///
        public static showContextMenu(contentMenuTarget: JQuery): void {
            var dia = $("#contextMenu-dialog");
            if (<any>contentMenuTarget.data("type") == "Directory") {
                dia.find(".checkout-context-command").hide();
                dia.find(".checkin-context-command").hide();
                dia.find(".rename-context-command").hide();
                dia.find(".download-context-command").hide();
                dia.find(".original-download-context-command").hide();
                dia.find(".remove-context-command").hide();
                dia.find(".history-context-command").hide();
                dia.find(".compremove-context-command").hide();
                dia.find(".accesslog-context-command").hide();
            } else {
                dia.find(".rename-context-command").show();
                dia.find(".download-context-command").show();
                dia.find(".original-download-context-command").show();
                dia.find(".remove-context-command").show();
                dia.find(".history-context-command").show();
                dia.find(".compremove-context-command").show();
                dia.find(".accesslog-context-command").show();

                dia.find(".removefolder-context-command").hide();
                var checkout = contentMenuTarget.find(".icon-pop-out");
                if (checkout.length == 0) {
                    dia.find(".checkout-context-command").show();
                    dia.find(".checkin-context-command").hide();
                } else {
                    dia.find(".checkout-context-command").hide();
                    dia.find(".checkin-context-command").show();
                }
            }
            dia.show();
            var pos = contentMenuTarget.find(".conetextMenuBtn").position();
            dia.css('top', pos.top);
            if (contentMenuTarget.find(".file-items-date").is(':visible')) {
                dia.css('left', pos.left);
            } else {
                dia.css('left', pos.left - dia.width() - contentMenuTarget.find(".conetextMenuBtn").width()/2);
            }
            $('.rename-context-command').unbind().click(function (e) {
                e.stopPropagation();
                dia.hide();
                $("#renameSrcPath").val(CloudStorageLight.StorageController.contentMenuTarget.find(".item-checkbox").attr("name"));
                $("#renameDistName").val(CloudStorageLight.StorageController.contentMenuTarget.find(".item-name").text());
                //$("#rename-directory-list").load(CloudStorageLight.StorageController.getHelperUrl("/DirectoryDropDownList") + "?name=renameDistDirectory&id=" + encodeURIComponent($("#currentPath").val()));
                $('#rename-dialog').dialog({
                    modal: true,
                    width: 300,
                    title: CloudStorageLight.StorageController.msgCmdRename,
                });
            });

            $('.remove-context-command').unbind().click(function (e) {
                e.stopPropagation();
                dia.hide();
                CloudStorageLight.StorageController.removeOne(CloudStorageLight.StorageController.contentMenuTarget, function () {
                    CloudStorageLight.StorageController.hideContextMenu(CloudStorageLight.StorageController.contentMenuTarget);
                });
            });

            $('.compremove-context-command').unbind().click(function (e) {
                e.stopPropagation();
                dia.hide();
                CloudStorageLight.StorageController.removeCompletelyOne(CloudStorageLight.StorageController.contentMenuTarget, function () {
                    CloudStorageLight.StorageController.hideContextMenu(CloudStorageLight.StorageController.contentMenuTarget);
                });
            });

            $('.removefolder-context-command').unbind().click(function (e) {
                e.stopPropagation();
                dia.hide();
                CloudStorageLight.StorageController.removeFolder(<any>CloudStorageLight.StorageController.contentMenuTarget.find(".blobfile").data("path"));
                CloudStorageLight.StorageController.hideContextMenu(CloudStorageLight.StorageController.contentMenuTarget);
            });


            $('.download-context-command').unbind().click(function (e) {
                e.stopPropagation();
                dia.hide();
                CloudStorageLight.StorageController.downloadOne(CloudStorageLight.StorageController.contentMenuTarget);
                CloudStorageLight.StorageController.hideContextMenu(CloudStorageLight.StorageController.contentMenuTarget);
            });
            $('.original-download-context-command').unbind().click(function (e) {
                e.stopPropagation();
                dia.hide();
                CloudStorageLight.StorageController.downloadOriginal(CloudStorageLight.StorageController.contentMenuTarget);
                CloudStorageLight.StorageController.hideContextMenu(CloudStorageLight.StorageController.contentMenuTarget);
            });
            $('.checkout-context-command').unbind().click(function (e) {
                e.stopPropagation();
                dia.hide();
                CloudStorageLight.StorageController.checkout(CloudStorageLight.StorageController.contentMenuTarget);
                CloudStorageLight.StorageController.hideContextMenu(CloudStorageLight.StorageController.contentMenuTarget);
            });

            $('.checkin-context-command').unbind().click(function (e) {
                e.stopPropagation();
                dia.hide();
                CloudStorageLight.StorageController.checkin(CloudStorageLight.StorageController.contentMenuTarget);
                CloudStorageLight.StorageController.hideContextMenu(CloudStorageLight.StorageController.contentMenuTarget);
            });


            $('.history-context-command').click(function (e) {
                e.stopPropagation();
                dia.hide();
                CloudStorageLight.StorageController.getVersions($("#file-items"),
                    CloudStorageLight.StorageController.contentMenuTarget.find(".item-checkbox").attr("name"),
                    <any>CloudStorageLight.StorageController.contentMenuTarget.find(".blobfile").data("href"));
                CloudStorageLight.StorageController.hideContextMenu(CloudStorageLight.StorageController.contentMenuTarget);
            });

            $('.accesslog-context-command').click(function (e) {
                e.stopPropagation();
                dia.hide();
                CloudStorageLight.StorageController.getAccessLog($("#file-items"), CloudStorageLight.StorageController.contentMenuTarget.find(".item-checkbox").attr("name"));
                CloudStorageLight.StorageController.hideContextMenu(CloudStorageLight.StorageController.contentMenuTarget);
            });

            $(".showurl-context-command").unbind().click(function (e) {
                e.stopPropagation();
                dia.hide();
                CloudStorageLight.StorageController.hideContextMenu(CloudStorageLight.StorageController.contentMenuTarget);
                $.Dialog({
                    flat: true,
                    overlay: true,
                    shadow: true,
                    title: CloudStorageLight.StorageController.msgItemUrl,
                    width: 300,
                    height: 100,
                    content: "<input type='text' readonly='readonly' id='itemUrl' style='width:100%;' value='" + StorageController.contentMenuTarget.find(".blobfile").attr("data-href") + "' />",
                    padding: 10,
                    onShow: function (_dialog) {
                        $("#itemUrl").focus();
                    }
                });
            });

            $("body").unbind().click(function () {
                dia.hide();
            });

            //$.Dialog({
            //    overlay: false,
            //    shadow: true,
            //    flat: true,
            //    content: '',
            //    onShow: function (_dialog) {
            //        var dia = _dialog.children('.content');
            //        var height = 250;
            //        dia.html($("#contextMenu-dialog").html());
            //        if (contentMenuTarget.data("type") == "Directory") {
            //            dia.find(".checkout-context-command").hide();
            //            dia.find(".checkin-context-command").hide();
            //            dia.find(".rename-context-command").hide();
            //            dia.find(".download-context-command").hide();
            //            dia.find(".remove-context-command").hide();
            //            dia.find(".history-context-command").hide();
            //            dia.find(".compremove-context-command").hide();
            //            height = 100;
            //        } else {
            //            dia.find(".removefolder-context-command").hide();
            //            var checkout = contentMenuTarget.find(".icon-pop-out");
            //            if (checkout.length == 0) {
            //                dia.find(".checkout-context-command").show();
            //                dia.find(".checkin-context-command").hide();
            //            } else {
            //                dia.find(".checkout-context-command").hide();
            //                dia.find(".checkin-context-command").show();
            //            }
            //        }
            //        dia.show();
            //        setTimeout(function () {
            //            var pos = contentMenuTarget.find(".conetextMenuBtn").position();
            //            _dialog.closest(".window").css('top', pos.top);
            //            _dialog.closest(".window").css('left', pos.left);
            //            _dialog.closest(".window").css('height', height);
            //            _dialog.closest(".window").css('min-height', height);
            //        },1);
            //        $('.rename-context-command').unbind().click(function () {
            //            $("#renameSrcPath").val(CloudStorageLight.StorageController.contentMenuTarget.find(".item-checkbox").attr("name"));
            //            $("#renameDistName").val(CloudStorageLight.StorageController.contentMenuTarget.find(".item-name").text());
            //            $("#rename-directory-list").load(CloudStorageLight.StorageController.getHelperUrl("/DirectoryDropDownList") + "?name=renameDistDirectory&id=" + encodeURIComponent($("#currentPath").val()));
            //            $('#rename-dialog').dialog({
            //                modal: true,
            //                width: 500,
            //                title: CloudStorageLight.StorageController.msgCmdRename,
            //            });
            //        });

            //        $('.remove-context-command').unbind().click(function (e) {
            //            CloudStorageLight.StorageController.removeOne(CloudStorageLight.StorageController.contentMenuTarget, function () {
            //                CloudStorageLight.StorageController.hideContextMenu(CloudStorageLight.StorageController.contentMenuTarget);
            //            });
            //        });

            //        $('.removefolder-context-command').unbind().click(function (e) {
            //            CloudStorageLight.StorageController.removeFolder(CloudStorageLight.StorageController.contentMenuTarget.find(".blobfile").data("path"));
            //            CloudStorageLight.StorageController.hideContextMenu(CloudStorageLight.StorageController.contentMenuTarget);
            //        });


            //        $('.download-context-command').unbind().click(function (e) {
            //            CloudStorageLight.StorageController.downloadOne(CloudStorageLight.StorageController.contentMenuTarget);
            //            CloudStorageLight.StorageController.hideContextMenu(CloudStorageLight.StorageController.contentMenuTarget);
            //        });
            //        $('.checkout-context-command').unbind().click(function (e) {
            //            CloudStorageLight.StorageController.checkout(CloudStorageLight.StorageController.contentMenuTarget);
            //            CloudStorageLight.StorageController.hideContextMenu(CloudStorageLight.StorageController.contentMenuTarget);
            //        });

            //        $('.checkin-context-command').unbind().click(function (e) {
            //            CloudStorageLight.StorageController.checkin(CloudStorageLight.StorageController.contentMenuTarget);
            //            CloudStorageLight.StorageController.hideContextMenu(CloudStorageLight.StorageController.contentMenuTarget);
            //        });


            //        $('.history-context-command').click(function (e) {
            //            CloudStorageLight.StorageController.getVersions($("#file-items"), CloudStorageLight.StorageController.contentMenuTarget.find(".item-checkbox").attr("name"));
            //            CloudStorageLight.StorageController.hideContextMenu(CloudStorageLight.StorageController.contentMenuTarget);
            //            e.stopPropagation();
            //        });


            //        $(".showurl-context-command").unbind().click(function () {
            //            CloudStorageLight.StorageController.hideContextMenu(CloudStorageLight.StorageController.contentMenuTarget);
            //            $.Dialog({
            //                flat: true,
            //                overlay: true,
            //                shadow: true,
            //                title: CloudStorageLight.StorageController.msgItemUrl,
            //                width: 300,
            //                height: 100,
            //                content: "<input type='text' readonly='readonly' id='itemUrl' style='width:100%;' value='" + StorageController.contentMenuTarget.find(".blobfile").attr("data-href") + "' />",
            //                padding: 10,
            //                onShow: function (_dialog) {
            //                    $("#itemUrl").focus();
            //                }
            //            });
            //        });


            //    }
            //});

        }

        ///
        /// 次のデータの取得
        ///
        public static morePage(size:number=200): void {
            var start = $("#file-items .list").length;

            var path = $("#currentPath").val();

            $(".morePage").empty().append('<img src="' + CloudStorageLight.StorageController.rootUrl + '/Content/Images/ajax-loader.gif">');
            var self = $(this);
            $.ajax(StorageController.getODataUrl(null, null) + "?$filter=Directory eq '" + StorageController.getEscapedPath(path) + "'&$skip=" + start.toString() + "&$top=" + (size + 1).toString(), {
                type: "GET",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    $(".morePage").remove();
                    $(data).children().appendTo($("#folder-cont"));
                    var cont = $("#file-items");
                    Enumerable.from(data.value)
                        .take(size)
                        .doAction(function (x) {
                            var obj = <FileItem>$.extend(new FileItem(), x);
                            var ele = $("#fileitem-template").tmpl(obj);
                            cont.append(ele);
                        }).toArray();
                    if (data.value.length > size) {
                        var more = $("#fileitem-more-template").tmpl();
                        cont.append(more);
                    }
                    StorageController.bindItemEvent();
                    StorageController.unblockUI();
                },
                error: function (xhr, textStatus, errorThrown) {
                    var cont = $("#file-items");
                    cont.append(StorageController.createErrorMessageElement(StorageController.getErrorMessage(xhr)));
                    StorageController.unblockUI();
                },
                dataType: "json"
            });

        }

        ///
        /// アップロード
        ///
        public static upload(data: any): void {
            StorageController.uploadQue.push(data);
            if (!StorageController.currentUpload) {
                StorageController.currentUpload = data;
                StorageController.blockUI(null);
                setTimeout(function () {
                    StorageController.uploadItem();
                }, 10);
            }
        }

        private static uploadItem(): void {
            if (StorageController.uploadQue.length == 0) {
                StorageController.currentUpload = null;
                StorageController.refresh();
            } else {
                StorageController.currentUpload = StorageController.uploadQue.shift();
                setTimeout(function () {
                    var filePath = $("#currentPath").val() + StorageController.currentUpload.files[0].name;
                    CloudStorageLight.StorageController.isExists(filePath, function (exists) {
                        if (exists) {
                            var overwrite = confirm(StorageController.formatString(StorageController.msgConfirmOverwriteUpload, [filePath]));
                            if (overwrite) {
                                $('#prog-message').text(StorageController.formatString(StorageController.msgUploading, [StorageController.currentUpload.files[0].name, StorageController.uploadQue.length + 1]));
                                StorageController.uploadItemSubmit();
                            } else {
                                StorageController.uploadItem();
                            }
                        } else {
                            $('#prog-message').text(StorageController.formatString(StorageController.msgUploading, [StorageController.currentUpload.files[0].name, StorageController.uploadQue.length + 1]));
                            StorageController.uploadItemSubmit();
                        }
                    });


                }, 10);
            }
        }

        private static uploadItemSubmit() {

            StorageController.currentUpload.submit()
                .error(function (jqXHR, textStatus, errorThrown) {
                    if (textStatus != "abort") {
                        alert(CloudStorageLight.StorageController.msgErrGeneral + " " + StorageController.currentUpload.files[0].name);
                        StorageController.uploadItem();
                    } else {
                        StorageController.uploadQue = [];
                        StorageController.currentUpload = null;
                    }
                })
                .complete(function (result, textStatus, jqXHR) {
                    if (textStatus == "error") return;
                    if (textStatus != "abort") {
                        if (!result.responseJSON) result.responseJSON = jqXHR.responseJSON;
                        if (!result.responseJSON.status) {
                            alert(result.responseJSON.data + " " + StorageController.currentUpload.files[0].name);
                        }
                        StorageController.uploadItem();
                    } else {
                        StorageController.uploadQue = [];
                        StorageController.currentUpload = null;
                    }
                });

        }

        ///
        /// 名前変更
        ///
        public static rename(target: JQuery, srcName: string, distName: string): void {
            if (!StorageController.startProcess(null, null, true, true)) return;
            StorageController.renameItem(target.find(".item-checkbox"), srcName, distName, null);
        }

        ///
        /// 名前変更
        ///
        public static renameItem(target: JQuery, srcName: string, distName: string, callback= null): void {
            var statusText = target.closest(".list").find(".list-remark");
            statusText.text("");
            var jsonData = JSON.stringify({ targetId: distName });
            $.ajax(StorageController.getODataUrl(target.attr("name"), "Rename"), {
                type: "POST",
                contentType: "application/json; charset=utf-8",
                data: jsonData,
                success: function (data) {
                    if ($("#currentPath").val() == StorageController.getParentFolderPath(distName)) {
                        var contents = target.closest(".list");
                        var obj = <FileItem>$.extend(new FileItem(), data);
                        var ele = $("#fileitem-template").tmpl(obj);
                        contents.html(ele.html());
                        StorageController.bindItemEvent(contents);
                    } else {
                        target.closest(".list").remove();
                    }              
                    StorageController.endProcessing();
                    if (callback) callback();
                },
                error: function (xhr, textStatus, errorThrown) {
                    statusText.text(StorageController.getErrorMessage(xhr));
                    StorageController.endProcessing();
                },
            });

        }

        ///
        /// 移動（チェックボックスで指定されたアイテム）
        ///
        public static move(distName: string): void {
            if (!StorageController.startProcess(null, null)) return;
            $(".item-checkbox:checked").each(function () {
                StorageController.renameItem($(this), $(this).attr("name"), distName);
            });
        }

        ///
        /// 削除（チェックボックスで指定されたアイテム）
        ///
        public static remove(removing= null): void {
            if (!StorageController.startProcess(function () {
                return confirm(StorageController.formatString(StorageController.msgConfirmDelete, $(".item-checkbox:checked").length));
            })) return;
            $(".item-checkbox:checked").each(function () {
                StorageController.removeItem($(this), removing);
            });
        }


        ///
        /// 回復（チェックボックスで指定されたアイテム）
        ///
        public static recover(): void {
            if (!StorageController.startProcess(null, null)) return;
            $(".item-checkbox:checked").each(function () {
                StorageController.recoverItem($(this));
            });
        }


        ///
        /// 完全削除（チェックボックスで指定されたアイテム）
        ///
        public static removeCompletely(removing= null): void {
            if (!StorageController.startProcess(function () {
                return confirm(StorageController.formatString(StorageController.msgConfirmCompetelyDelete, $(".item-checkbox:checked").length));
            })) return;
            $(".item-checkbox:checked").each(function () {
                StorageController.removeCompletelyItem($(this), removing);
            });
        }

        ///
        /// 完全削除（個別指定）
        ///
        public static removeCompletelyOne(target: JQuery, removing= null): void {
            if (!StorageController.startProcess(function () {
                return confirm(StorageController.formatString(StorageController.msgConfirmDeleteCompletelyFile, target.find(".item-name").text()));
            }, null, true, true)) return;
            StorageController.removeCompletelyItem(target.find(".item-checkbox"), removing);
        }

        


        ///
        /// 削除（個別指定）
        ///
        public static removeOne(target: JQuery, removing= null): void {
            if (!StorageController.startProcess(function () {
                return confirm(StorageController.formatString(StorageController.msgConfirmDeleteFile, target.find(".item-name").text()));
            }, null, true, true)) return;
            StorageController.removeItem(target.find(".item-checkbox"), removing);
        }


        private static removeItem(target: JQuery, removing= null): void {

            $.ajax(StorageController.getODataUrl(target.attr("name"), null), {
                type: "DELETE",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    var contents = target.closest(".list");
                    if (removing) removing();
                    contents.remove();
                    StorageController.endProcessing();
                },
                error: function (xhr, textStatus, errorThrown) {
                    var statusText = target.closest(".list").find(".list-remark");
                    statusText.text(StorageController.getErrorMessage(xhr));
                    StorageController.endProcessing();
                },
            });
        }

        private static recoverItem(target: JQuery, recovering= null): void {

            var path = target.attr("name");
            $.ajax(StorageController.getODataUrl(path, "Recover"), {
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    var contents = target.closest(".list");
                    if (recovering) recovering();
                    contents.remove();
                    StorageController.endProcessing();
                },
                error: function (xhr, textStatus, errorThrown) {
                    var statusText = target.closest(".list").find(".list-remark");
                    statusText.text(StorageController.getErrorMessage(xhr));
                    StorageController.endProcessing();
                },
            });
        }

        public static isBackupOn(target: JQuery, callback= null): void {

            var path = target == null ? $("#currentPath").val() : target.attr("name");
            $.ajax(StorageController.getODataUrl(path, "IsBackupOn"), {
                type: "GET",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    if (callback) callback(data);
                },
                error: function (xhr, textStatus, errorThrown) {
                    if (callback) callback(null);
                },
            });
        }

        public static isExists(path: string, callback= null): void {

            $.ajax(StorageController.getODataUrl(path, "IsExists"), {
                type: "GET",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    if (callback) callback(data.value);
                },
                error: function (xhr, textStatus, errorThrown) {
                    if (callback) callback(null);
                },
            });
        }

        private static removeCompletelyItem(target: JQuery, removing= null): void {

            $.ajax(StorageController.getODataUrl(target.attr("name"), "DeleteCompletely"), {
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    var contents = target.closest(".list");
                    if (removing) removing();
                    contents.remove();
                    StorageController.endProcessing();
                },
                error: function (xhr, textStatus, errorThrown) {
                    var statusText = target.closest(".list").find(".list-remark");
                    statusText.text(StorageController.getErrorMessage(xhr));
                    StorageController.endProcessing();
                },
            });
        }

        public static startCrawl(path: string): void {

            $.ajax(StorageController.getODataUrl(path, "StartCrawl"), {
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    alert(StorageController.msgSuccess);
                    StorageController.endProcessing();
                },
                error: function (xhr, textStatus, errorThrown) {
                    alert(StorageController.getErrorMessage(xhr));
                    StorageController.unblockUI();
                },
            });
        }


        ///
        /// ダウンロード（チェックボックスで指定されたアイテム）
        ///
        public static download(): void {

            if (!StorageController.startProcess(null, null, false)) return;
            var que: JQuery[] = [];
            $(".item-checkbox:checked").each(function () {
                que.push($(this).closest(".list").find(".blobfile"));
            });
            StorageController.downloadfile(que);

        }

        ///
        /// ダウンロード（個別指定）
        ///
        public static downloadOne(target: JQuery): void {
            if (!StorageController.startProcess(null, null, false, true)) return;
            var que: JQuery[] = [];
            que.push(target.find(".blobfile"));
            StorageController.downloadfile(que);

        }

        public static downloadOriginal(target: JQuery): void {
            window.location.href = <any>(target.find(".blobfile").data("href"));
        }
        
        ///
        /// ダウンロード ZIP（チェックボックスで指定されたアイテム）
        ///
        public static downloadZip(actionUrl: string): void {
            if (!StorageController.startProcess()) return;
            var files = {};
            $(".item-checkbox:checked").each(function (idx) {
                files["file" + idx.toString()] = $(this).attr("name");
            });

            setTimeout(function () {

                $.fileDownload(
                    actionUrl, {
                        httpMethod: "POST",
                        data: files,
                        successCallback: function (url) {
                            StorageController.endProcessing(true);

                        },
                        failCallback: function (html, url) {
                            StorageController.endProcessing(true);
                            var error = StorageController.getCookie("errormessage");
                            alert(CloudStorageLight.StorageController.msgDownloadError + " " + (error ? error : ""));
                        }
                    });
            }
                , 100);
        }
 
        private static downloadfile(que: JQuery[]): void {
            if (que.length == 0) {
                StorageController.endProcessing(true);
                return;
            }
            var target = que.shift();
            var url = <any>target.data("href");
            //if (url.indexOf("?") >= 0) {
            //    url = url + "&setcookie=1";
            //} else {
            //    url = url + "?setcookie=1";
            //}
            $('#prog-message').text(StorageController.formatString(StorageController.msgDownloading, [target.find(".item-name").text(), que.length + 1]));
            setTimeout(function () {

                $.fileDownload(
                    url, {
                        successCallback: function (url) {
                            StorageController.downloadfile(que);
                            var statusText = target.find(".list-remark");
                            statusText.text(CloudStorageLight.StorageController.msgDownloadComplete);
                        },
                        failCallback: function (html, url) {
                            var error = StorageController.getCookie("errormessage");
                            StorageController.downloadfile(que);
                            var statusText = target.find(".list-remark");
                            statusText.text(CloudStorageLight.StorageController.msgDownloadError + " " + (error ? error : ""));
                        }
                    });
            }, 100);
        }

        public static getCookie(name: string) {
            var result = null;

            var cookieName = name + '=';
            var allcookies = document.cookie;

            var position = allcookies.indexOf(cookieName);
            if (position != -1) {
                var startIndex = position + cookieName.length;

                var endIndex = allcookies.indexOf(';', startIndex);
                if (endIndex == -1) {
                    endIndex = allcookies.length;
                }

                result = decodeURIComponent(
                    allcookies.substring(startIndex, endIndex));
            }
            return result;
        }


        ///
        /// フォルダ作成
        ///
        public static createNewFolder(): void {
            $('#create-folder-dialog').dialog("close");
            StorageController.blockUI(null);
            var jsonData = JSON.stringify({ directoryName: $('#newFolderName').val(), ensure:false });
            $.ajax(StorageController.getODataUrl($("#currentPath").val() , "CreateDirectory"), {
                type: "POST",
                contentType: "application/json; charset=utf-8",
                data: jsonData,
                success: function (data) {
                    StorageController.unblockUI();
                    StorageController.refresh();
                },
                error: function (xhr, textStatus, errorThrown) {
                    alert(StorageController.getErrorMessage(xhr));
                    StorageController.unblockUI();
                },
                dataType: "json"
            });
        }

        ///
        /// フォルダ削除
        ///
        public static removeFolder(path:string = null): void {
            if (path == null) path = $("#currentPath").val();
            if (!confirm(StorageController.formatString(StorageController.msgConfirmDeleteFolder, path))) {
                return;
            }

            StorageController.blockUI(null);
            $.ajax(StorageController.getODataUrl(path, null), {
                type: "DELETE",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    window.location.href = StorageController.getParentFolderPath(window.location.href) + location.search;
                },
                error: function (xhr, textStatus, errorThrown) {
                    alert(StorageController.getErrorMessage(xhr));
                    StorageController.unblockUI();
                },
            });
        }


        private static setAccessToken(target: JQuery, token: FileAccessToken) {
            target.find(".accessToken-inuse").prop("checked", token.inUse);  
            target.find(".accessToken-name").val( token.role);  
            target.find(".accessToken-can-read").prop("checked", token.canRead);  
            target.find(".accessToken-can-write").prop("checked", token.canWrite);  
            target.find(".accessToken-can-modify").prop("checked", token.canModify);  
            target.find(".accessToken-can-control").prop("checked", token.canControl);  
        }

        ///
        /// フォルダ設定表示
        ///
        public static setupFolder(): void {
            $("#directorySettings").dialog(<any>{
                width: 800,
                height: 500,
                modal: true,
                title: StorageController.msgCmdFolderSetup,
                open: function () {
                    $(this).html("<div style='text-align:center;margin-top:15%;'><img src='" + CloudStorageLight.StorageController.rootUrl + "/Content/Images/ajax-loader.gif' ></div>");
                    $(this).load(StorageController.getHelperUrl("/ShowBlobDirectorySettings"), { id: $("#currentPath").val() });
                },
            });

        }

        ///
        /// フォルダ設定実行
        ///
        public static updateFolder(): void {
            StorageController.blockUI(null);

            var accessTokens:string[] = [];

            $("#directory-access-list .accessToken-inuse").each(function () {
                var inuse = $(this);
                var parent = $(this).closest("tr");
                if (inuse.prop("checked") && parent.find(".accessToken-name").val()) {
                    var token = new FileAccessToken();
                    token.inUse = true;
                    token.role = parent.find(".accessToken-name").val();
                    token.canRead = parent.find(".accessToken-can-read").prop("checked");
                    token.canWrite = parent.find(".accessToken-can-write").prop("checked");
                    token.canModify = parent.find(".accessToken-can-modify").prop("checked");
                    token.canControl = parent.find(".accessToken-can-control").prop("checked");
                    accessTokens.push(token.toString());
                }
            });

            var jsonData = $('#blobItemDetailForm').serialize();

            $.ajax(StorageController.getHelperUrl("/UpdateBlobDirectorySettings"), {
                type: "POST",
                data: jsonData,
                success: function (data) {
                    if (data == "") {
                        StorageController.unblockUI();
                        $("#directorySettings").dialog("close");
                    } else {
                        alert(data);
                    }
                },
                error: function (xhr, textStatus, errorThrown) {
                    StorageController.unblockUI();
                    alert(StorageController.getErrorMessage(xhr));
                },
            });
        }

        ///
        /// フォルダ設定閉じる
        ///
        public static closeUpdateFolderDialog(): void {
            $("#directorySettings").dialog("close");
        }

        public static transferFile(): void {
            if ($(".item-checkbox:checked").length == 0) {
                alert(StorageController.msgPleaseChecked);
                return;
            }
            $("#fileTransfer").dialog(<any>{
                width: 800,
                height: 570,
                modal: true,
                title: StorageController.msgFileTransfer,
                open: function () {
                    $(this).html("<div style='text-align:center;margin-top:15%;'><img src='" + CloudStorageLight.StorageController.rootUrl + "/Content/Images/ajax-loader.gif' ></div>");
                    $(this).load(StorageController.getWorkTaskUrl("/ShowFileTransfer"), { id: $("#currentPath").val() });
                },
            });

        }

        public static sendMailTransferFile(): void {
            StorageController.blockUI(null);

            var jsonData = $('#fileTransferForm').serialize();

            $.ajax(StorageController.getWorkTaskUrl("/SendFile"), {
                type: "POST",
                data: jsonData,
                success: function (data) {
                    if (data == "") {
                        StorageController.unblockUI();
                        $("#fileTransfer").dialog("close");
                    } else {
                        StorageController.unblockUI();
                        $("#fileTransferForm").parent().html(data);
                    }
                },
                error: function (xhr, textStatus, errorThrown) {
                    StorageController.unblockUI();
                    alert(StorageController.getErrorMessage(xhr));
                },
            });
        }

        public static closetransferFileDialog(): void {
            $("#fileTransfer").dialog("close");
        }

        ///
        /// 検索処理
        ///
        public static search(query: string, current: string, cont: JQuery): void {

            if (StorageController.isBlock()) return;
            if (query == null || query == "" || query.trim() == "") {
                StorageController.getFiles(cont, current);
            } else {
                StorageController.searchFiles(cont, current, query);
            }
        }

 
        public static hideContextMenu(contentMenuTarget: JQuery): void {
            $.Dialog.close();

        }

        ///
        /// チェックアウト
        ///
        public static checkout(target: JQuery): void {
            if (!StorageController.startProcess(null, null, true, true)) return;
            StorageController.checkoutItem(target.find(".item-checkbox"));
        }

        public static checkoutItem(target: JQuery): void {
            StorageController.allSuccess = true;
            $.ajax(StorageController.getODataUrl(target.attr("name"), "Checkout"), {
                type: "POST",
                success: function (data) {
                    var contents = target.closest(".list");
                    var obj = <FileItem>$.extend(new FileItem(), data);
                    var ele = $("#fileitem-template").tmpl(obj);
                    contents.html(ele.html());
                    StorageController.bindItemEvent(contents);
                    StorageController.endProcessing();
                },
                error: function (xhr, textStatus, errorThrown) {
                    var statusText = target.closest(".list").find(".list-remark");
                    statusText.text(StorageController.getErrorMessage(xhr));
                    StorageController.endProcessing();
                    StorageController.allSuccess = false;
                },
                dataType: "json"
            });
        }

        ///
        /// チェックイン
        ///
        public static checkin(target: JQuery): void {
            if (!StorageController.startProcess(function () {
                var owner = target.find(".checkout-user").attr("title");
                if (owner != $("#currentUser").val()) {
                    return confirm(StorageController.msgConfirmForceCheckin);
                }
                else
                {
                    return true;
                }
            }, null, true, true)) return;
            StorageController.checkinItem(target.find(".item-checkbox"));
        }

        public static checkinItem(target: JQuery): void {
            var self = $(this);
            $.ajax(StorageController.getODataUrl(target.attr("name"), "Checkin"), {
                type: "POST",
                success: function (data) {
                    var contents = target.closest(".list");
                    var obj = <FileItem>$.extend(new FileItem(), data);
                    var ele = $("#fileitem-template").tmpl(obj);
                    contents.html(ele.html());
                    StorageController.bindItemEvent(contents);
                    StorageController.endProcessing();
                },
                error: function (xhr, textStatus, errorThrown) {
                    var statusText = target.closest(".list").find(".list-remark");
                    statusText.text(StorageController.getErrorMessage(xhr));
                    StorageController.endProcessing();
                },
                dataType: "json"
            });
        }


        ///
        /// ユーリティティ
        ///

        public static getHelperUrl(url: string): string {
            return StorageController.helperRootUrl + url;
        }
        public static getWorkTaskUrl(url: string): string {
            return StorageController.workTaskRootUrl + url;
        }
        public static getAccountUrl(url: string): string {
            return StorageController.accountRootUrl + url;
        }
        public static getODataUrl(path: string, action: string): string {
            var works = (path ? path : "").split("/");
            for (var i = 0; i < works.length; i++) {
                works[i] = encodeURIComponent(decodeURIComponent(works[i]).replace("'", "''"));
            }
            path = works.join("/");
            var url = StorageController.oDataRootUrl + "/Data";
            if (path) {
                url += "('" + path.replace(/\./g, "*").replace(/\//g, "|") + "')"
            }
            if (action) {
                url += "/StorageService." + action;
            }
            return url;
        }

        ///
        /// ユーザ管理
        ///

        private static grouplistcont: string;

        ///ユーザ検索
        public static searchUsers(query: string): void {
            window.location.href = window.location.pathname + "?query=" + encodeURI(query);
        }

        ///
        /// ユーザ情報表示HTMLにイベントをバインドする
        ///
        public static bindUserList(): void {
            $(".role-select").unbind().click(function () {
                StorageController.roleSelect($(this).closest(".list").find(".role-list"));
            });
            $(".role-admin input").unbind().click(function () {
                StorageController.setDirtyUserList($(this).closest(".list"), true);
            });
            $(".isDeliverablesRecommendMail input").unbind().click(function () {
                StorageController.setDirtyUserList($(this).closest(".list"), true);
            });
            $(".userSaveButton").unbind().click(function () {
                StorageController.saveUser($(this).closest(".list"));
            });
            $(".delete-user").unbind().click(function () {
                StorageController.deleteUser($(this).closest(".list"));
            });
        }

        ///
        /// ユーザ追加
        ///
        public static showAddUser(): void {
            var groupList = $("#addUserForm").dialog(<any>{
                modal: true,
                height: 300,
                width: 500,
                title: StorageController.msgRoleSelectorTitle,
                open: function () {
                    $("#username").val("");
                    $("#userpassword").val("");
                    $("#confirmuserpassword").val("");
                    $('#adduser').unbind().click(function () {
                        var username = $("#username").val();
                        var data = $('#addUserForm').serialize();
                        $.ajax(StorageController.getAccountUrl("/AddUser"), {
                            type: "POST",
                            data: data,
                            success: function (data) {
                                if (data == "") {
                                    $("#addUserForm").dialog("close");
                                    $.get(StorageController.getAccountUrl("/GetUser")+"?username=" + username, function (newData) {
                                        var newItem = $(newData);
                                        $("#users-cont").prepend(newItem);
                                        $("#users-cont").scrollTop(0);
                                        StorageController.bindUserList();
                                    });
                                    StorageController.bindUserList();
                                } else {
                                    alert(data);
                                }
                            },
                            error: function (data) {
                                alert(StorageController.msgErrGeneral);
                                StorageController.unblockUI();
                            },
                            dataType: "html"
                        });
                    });
                },
            });

        }

        ///
        /// ユーザ情報を保存する
        ///
        public static saveUser(contents: JQuery): void {
            var statusText = contents.find(".list-remark");
            $(".list-remark").text("");
            StorageController.blockUI(null);
            $.ajax(StorageController.getAccountUrl("/UpdateUser"), {
                type: "POST",
                data: {
                    username: contents.find(".list-title").text(),
                    roles: contents.find(".role-list").text(),
                    isAdmin: contents.find(".role-admin input").prop("checked"),
                    isDeliverablesRecommendMail: contents.find(".isDeliverablesRecommendMail input").prop("checked"),
                },
                success: function (data) {
                    StorageController.unblockUI();
                    StorageController.setDirtyUserList(contents, false);
                    if (data == "") {
                        contents.load(StorageController.getAccountUrl("/GetUser") + "?username=" + contents.find(".list-title").text(), function () {
                            var newContents = $(this).children(':first').unwrap();
                            newContents.find(".list-remark").text(StorageController.msgUpdateUserData);
                            StorageController.bindUserList();
                        });
                        StorageController.bindUserList();
                    } else {
                        statusText.text(data);
                    }
                },
                error: function (data) {
                    statusText.text(StorageController.msgErrGeneral);
                    StorageController.unblockUI();
                },
                dataType: "html"
            });

        }

        ///
        /// ユーザ情報を削除する
        ///
        public static deleteUser(contents: JQuery): void {
            var statusText = contents.find(".list-remark");
            statusText.text("");
            var username = contents.find(".list-title").text();
            if (confirm(StorageController.formatString(StorageController.msgConfirmDeleteUser, username))) {
                StorageController.blockUI(null);
                $.ajax(StorageController.getAccountUrl("/DeleteUser"), {
                    type: "POST",
                    data: {
                        username: username,
                    },
                    success: function (data) {
                        StorageController.unblockUI();
                        if (data == "") {
                            contents.remove();
                        } else {
                            statusText.text(data);
                        }
                    },
                    error: function (data) {
                        statusText.text(StorageController.msgErrGeneral);
                        StorageController.unblockUI();
                    },
                    dataType: "html"
                });

            }
        }

        ///
        /// ロールを選択します
        ///
        private static roleSelect(contents: JQuery): void {
            var self = contents;
            var currentList = contents.text();

            $("#tools-dialog .list-remark").text("");

            var groupList = $("#grouplist").dialog(<any>{
                modal: true,
                height: 300,
                width: 400,
                title: StorageController.msgRoleSelectorTitle,
                open: function () {
                    $("#newRole").val("");
                    $('#addNewRole').unbind().click(function () {
                        StorageController.addNewRole(self);
                    });
                    $('#rolesave').unbind().click(function () {
                        StorageController.roleSelectSave(self);
                        groupList.dialog("close");
                    });
                    $('#roleclose').unbind().click(function () {
                        groupList.dialog("close");
                    });
                    $("#grouplist input").prop("checked", false);
                    if (currentList) {
                        currentList.split(",").forEach(function (val) {
                            $("#grouplist input[name='" + val + "']").prop("checked", true);
                            $("#grouplist .group2").each(function () {
                                if ($(this).find("input[type='text']").val() == val) {
                                    $(this).find("input[type='checkbox']").prop("checked", true);
                                }
                            });
                        });
                    }
                },
            });

        }

        ///
        /// ロールを追加する
        ///
        private static addNewRole(roleElement: JQuery): void {

            var role = $("#newRole").val();
            if ($("#grouplist input[name='" + role + "']").length > 0) {
                alert(StorageController.formatString(StorageController.msgDuplicateRole, role));
                return;
            }
            $("#grouplist ul").prepend("<li><input name='" + role + "' type='checkbox' checked='checked'><span>" + role + "</span></li>");
            role = $("#newRole").val("");
        }

        ///
        /// ロールを選択を決定する
        ///
        private static roleSelectSave(roleElement: JQuery): void {
            var list = "";
            $("#grouplist input:checked").each(function () {
                if (list != "") list += ",";
                list += $(this).attr("name");
            });
            roleElement.text(list);
            StorageController.setDirtyUserList(roleElement.closest(".list"), true);
        }


        ///
        /// ユーザ一覧の変更をマークする
        ///
        private static setDirtyUserList(contents: JQuery, value: boolean): void {
            if (value) {
                contents.addClass("marked");
                contents.find(".userSaveButton").attr('disabled', <any>false);

            } else {
                contents.removeClass("marked");
                contents.find(".userSaveButton").removeAttr('disabled');
            }
        }

        ///
        /// カスタム認証情報のクリア
        ///
        public static clearCustomAuth() {
            ;
            $.ajax(StorageController.getHelperUrl("/ClearCustomAuthInfo/"), {
                type: "POST",
                data: "id=" + encodeURIComponent($("#currentPath").val()),
                success: function (data) {
                    window.location.href = window.location.href;
                },
                error: function (xhr, textStatus, errorThrown) {
                    StorageController.unblockUI();
                    alert(StorageController.getErrorMessage(xhr));
                },
            });
        } 


        private static abortAll(): void {
            $(StorageController.xhrPool).each(function (idx, jqXHR: any) {
                jqXHR.abort();
            });
            CloudStorageLight.StorageController.xhrPool = [];
        }

        private static getParentFolderPath(path: string) {
            var items = path.split("?")[0].split("/");
            if (items.length <= 1) return "/";
            if (items.pop() == "") items.pop();
            return items.join("/") + "/";
        }

        private static formatString(fmt: string, a: any): string {
            var rep_fn = undefined;

            var rep_fn = undefined;

            if (typeof a == "object") {
                rep_fn = function (m, k) { return a[k]; }
            }
            else {
                var args = arguments;
                rep_fn = function (m, k) { return args[parseInt(k) + 1]; }
            }

            return fmt.replace(/\{(\w+)\}/g, rep_fn);
        }

        private static refresh(path: string = null): void {
            StorageController.blockUI(null);
            window.location.href = window.location.href;
            $('body,html').animate({
                scrollTop: 0
            }, 100);
        }

        private static blockUI(cont: JQuery, cancelable:boolean=true): void {
            $('#freezePanel').remove();
            if (!cont) {
                var cont = $("#maindiv");
                var cont2 = $("body");
                if (cont.height() < cont2.height()) cont = cont2;
            }
            if (cancelable) {
                $('body,html').animate({
                    scrollTop: 0
                }, 100);

                var wrap = $('<div id="freezePanel" style="postion:relative;height:0;width:0;"><div class="freezePaneOn"></div><div class="innerFreezePane"><div class="prog-cont"><div id="prog-message">' + StorageController.msgProcessing + '</div></div><div><img src="' + CloudStorageLight.StorageController.rootUrl + '/Content/Images/ajax-loader.gif"></div><div class=prog-percent></div><div><a id="prog-cancel" href="javascript:void(0);">' + StorageController.msgCancel + '</a></div></div></div>');
                $(cont).append(wrap);
                wrap.find(".freezePaneOn").height(cont.height());
                wrap.find("#prog-cancel").click(function () {
                    StorageController.abortAll();
                    StorageController.unblockUI();
                });
            } else {
                var wrap = $('<div id="freezePanel" style="postion:relative;height:0;width:0;"><div class="freezePaneOn"></div><div class="innerFreezePaneMini"><div><img src="' + CloudStorageLight.StorageController.rootUrl + '/Content/Images/ajax-loader.gif"></div></div>');
                $(cont).append(wrap);
                wrap.find(".freezePaneOn").height(cont.height());
            }
            $('#freezePaneOn').focus();
        }

        private static isBlock(): boolean {
            return $("#freezePanel").length != 0;
        }

        private　static unblockUI(): void {
            $('#freezePanel').remove();
        }

        private　static startProcess(confirm: any= null, callback: any= null, unblockAjaxStop: boolean = true, skipAlert: boolean= false): boolean {
            if (!skipAlert && $(".item-checkbox:checked").length == 0) {
                alert(StorageController.msgPleaseChecked);
                return false;
            } else {
                if (confirm && !confirm()) return;
                StorageController.blockUI(null);
                if (unblockAjaxStop) {
                    $(document).one("ajaxStop", function () {
                        StorageController.unblockUI();
                        if (callback) { callback(); }
                    });
                }
                StorageController.clearMessage();
                return true;
            }
        }

        private　static clearMessage(): void {
            $(".item-checkbox").each(function () {
                var statusText = $(this).closest(".list").find(".list-remark");
                statusText.text("");
            });
            $(".search-result-message").empty();
        }

        private　static endProcessing(force: boolean= false): void {
            if (force) StorageController.unblockUI();
        }

        private static endsWith(str: string, suffix: string): boolean {
            return str.indexOf(suffix, str.length - suffix.length) !== -1;
        }

        private static getErrorMessage(xhr): string {
            try {
                if (xhr.statusText == "abort") {
                    return StorageController.msgCanceled;
                }
                if (xhr.status == 404) {
                    return StorageController.msg404Error;
                }
                var responseJSON = <any>$.parseJSON(xhr.responseText);
                if (responseJSON && responseJSON.error && responseJSON.error.message) {
                    return responseJSON.error.message;
                } else {
                    return StorageController.msgErrGeneral;
                }
            } catch (e) {
                return StorageController.msgErrGeneral;
            };
        }

        private static createErrorMessageElement(msg: string): JQuery {
            return $("<p class='validation-summary-errors'>" + msg +"</p>");
        }
        private static createInfoMessageElement(msg: string): JQuery {
            return $("<p class='info'>" + msg + "</p>");
        }

    }

}

$(function () {

    $.ajaxSetup({
        beforeSend: function (jqXHR) {
            CloudStorageLight.StorageController.xhrPool.push(jqXHR);
        },
        complete: function (jqXHR) {
            var index = CloudStorageLight.StorageController.xhrPool.indexOf(jqXHR);
            if (index > -1) {
                CloudStorageLight.StorageController.xhrPool.splice(index, 1);
            }
        }
    });


    $('#search').click(function () {
        CloudStorageLight.StorageController.search($("#query").val(), $("#currentPath").val(), $("#file-items"));
    });

    $("#query").keypress(function (e) {
        if (e.keyCode == 13) {
            CloudStorageLight.StorageController.search($("#query").val(), $("#currentPath").val(), $("#file-items"));
        }
    });

    $('#newfolder-command').click(function () {
        $('#create-folder-dialog').dialog({
            modal: true,
            title: CloudStorageLight.StorageController.msgCmdNewFolder,
        });
    });
    $('#removefolder-command').click(function () {
        CloudStorageLight.StorageController.removeFolder();
    });


    $('#rename-command').click(function () {
        CloudStorageLight.StorageController.rename(CloudStorageLight.StorageController.contentMenuTarget,
            $("#renameSrcPath").val(), $("#renameDistDirectory").val() + $("#renameDistName").val());
        $('#rename-dialog').dialog("close");
        CloudStorageLight.StorageController.hideContextMenu(CloudStorageLight.StorageController.contentMenuTarget);
    });

    $('#move-command').click(function () {
        if ($(".item-checkbox:checked").length == 0) {
            alert(CloudStorageLight.StorageController.msgPleaseChecked);
            return false;
        }

        $("#move-directory-list").load(CloudStorageLight.StorageController.getHelperUrl("/DirectoryDropDownList") + "?name=moveDistDirectory&id=" + encodeURIComponent($("#currentPath").val()));

        $('#move-dialog').dialog({
            modal: true,
            width: 400,
            title: CloudStorageLight.StorageController.msgCmdMove,
        });
    });
    $('#move-exec-command').click(function () {
        CloudStorageLight.StorageController.move($("#moveDistDirectory").val());
        $('#move-dialog').dialog('close');
    });

    $('#upload-command').click(function () {
        $('#upl').click();
    });



    $('#remove-command').click(function () {
        CloudStorageLight.StorageController.remove();
    });


    $('#recover-command').click(function () {
        CloudStorageLight.StorageController.recover();
    });

    $('#compremove-command').click(function () {
        CloudStorageLight.StorageController.removeCompletely();
    });
    $('#clear-customauth-command').click(function () {
        CloudStorageLight.StorageController.clearCustomAuth();
    });

    $('#compremove-context-command').click(function (e) {
        CloudStorageLight.StorageController.removeCompletelyOne(CloudStorageLight.StorageController.contentMenuTarget, function () {
            CloudStorageLight.StorageController.hideContextMenu(CloudStorageLight.StorageController.contentMenuTarget);
        });
        e.stopPropagation();
    });



    $('#download-command').click(function () {
        if ($(".item-checkbox:checked").length > 1) {
            $("#download-confirm-dialog").dialog({
                modal: true,
            });

        } else {
            CloudStorageLight.StorageController.download();
        }
    });

    $('#download-zip-command').click(function () {
        CloudStorageLight.StorageController.downloadZip(CloudStorageLight.StorageController.getHelperUrl("/DownloadAsZip"));
        $("#download-confirm-dialog").dialog("close");
    });
    $('#download-files-command').click(function () {
        CloudStorageLight.StorageController.download();
        $("#download-confirm-dialog").dialog("close");
    });




    $('#create-newFolder').click(function () {
        CloudStorageLight.StorageController.createNewFolder();

    });

    $('#folder-setup-command').click(function () {
        CloudStorageLight.StorageController.setupFolder();
    });

    $('#selectall-command').click(function () {
        $(".item-checkbox").prop("checked", true);
    });
    $('#unselectall-command').click(function () {
        $(".item-checkbox").prop("checked", false);
    });

    $('#list-deleted-command').click(function (e) {
        CloudStorageLight.StorageController.listDeletedFiles($("#file-items"), $("#currentPath").val());
    });
    $("#transfer-file-command").click(function () {
        CloudStorageLight.StorageController.transferFile();
    });
});
